package servlet;

import com.alibaba.fastjson.JSON;
import entity.Commodity;
import entity.User;
import service.CollectionService;
import service.impl.CollectionServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "CollectionServlet", value = "/CollectionServlet")
public class CollectionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String opr = request.getParameter("opr");

        CollectionService collectionService = new CollectionServiceImpl();
        if("collection".equals(opr)){
            int userId = Integer.parseInt(request.getParameter("userId"));
            int commId = Integer.parseInt(request.getParameter("commId"));
            int result = collectionService.add(userId,commId);
            if(result>0){
                response.getWriter().print("true");
            }else{
                response.getWriter().print("false");
            }
        }
        if("isExist".equals(opr)){
            int id = Integer.parseInt(request.getParameter("id"));
            int userId = ((User)request.getSession().getAttribute("user")).getId();
            boolean flag = collectionService.findExist(userId,id);
            request.setAttribute("flag",flag);
            request.getRequestDispatcher("frontEnd/commInfo.jsp").forward(request,response);
        }
        if("showCollection".equals(opr)){
            int userId = ((User)request.getSession().getAttribute("user")).getId();
            int curr = Integer.parseInt(request.getParameter("curr"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            List<Commodity> byUserId = collectionService.findByUserId(userId,(curr-1)*limit,limit);
            response.getWriter().print(JSON.toJSONString(byUserId));
        }
        if("sumCountCollection".equals(opr)){
            int userId = ((User)request.getSession().getAttribute("user")).getId();
            int countByUserId = collectionService.findCountByUserId(userId);
            System.out.println(countByUserId);
            response.getWriter().print(countByUserId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
